﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utils.Collections;
using Utils.App;

namespace Utils.Drawing
{
    public class GOManagerView<T> where T : GOAdapter, new()
    {
        protected Pool<T> pool;
        protected List<T> list;
        protected GOAbstractManager goManager;

        public GOManagerView(GOAbstractManager goManager)
        {
            this.goManager = goManager;
            goManager.GOCreateEvent += OnGOCreateEvent;
            goManager.GODestroyEvent += OnGODestroyEvent;
            pool = new Pool<T>(goManager.PoolSize);
            list = new List<T>(goManager.PoolSize);
        }

        protected virtual void OnGOCreateEvent(object sender, EventArgs e)
        {
            GameObject go = sender as GameObject;
            if (go != null)
            {
                T adapter = pool.Get();
                adapter.InitGo(go);
                list.Add(adapter);
                OnAdapterAdded(adapter);
            }
        }

        protected virtual void OnGODestroyEvent(object sender, EventArgs e)
        {
            GameObject go = sender as GameObject;
            if (go != null)
            {
                foreach (T adapter in list)
                {
                    if (adapter.Owner == go)
                    {
                        list.Remove(adapter);
                        pool.Redeem(adapter);
                        OnAdapterDestroyed(adapter);
                        break;
                    }
                }
            }
        }

        protected virtual void OnAdapterAdded(T adapter) { }
        protected virtual void OnAdapterDestroyed(T adapter) { }

        public virtual void Draw(float dTime, SpriteRenderer renderer)
        {
            foreach (T adapter in list)
            {
                adapter.Draw(dTime, renderer);
            }
        }

        public virtual void DrawPrimitives(float dTime, PrimitiveRenderer renderer)
        {
            foreach (T adapter in list)
            {
                adapter.DrawPrimitives(dTime, renderer);
            }
        }
    }
}
